<template>
  <div class="_wz_trajectory" style="height: 100%;width: 100%;">
    <div class="baidumap" id="_wz_vehicleMonitoring_allmap" style="height: 100%;width: 100%;"></div>
  </div>
</template>

<script>


import {getCurrentInstance,inject,nextTick,reactive, toRefs,toRef,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted, ref,defineComponent,toRaw,watch} from 'vue'
import { useRouter,useRoute } from "vue-router";

import { useMainStore } from '../../../store'  //pinia 使用 类似 vuex
import { storeToRefs } from 'pinia'//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex

//reactive
export default defineComponent({
  name: 'trajectory',//组件名称
  props: ['currentTravelLogId'],//接收来自父组件的数据
  components: {},//组件引用
  setup (props,context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用
    const $common = inject('$common');//自己封装的方法


    const state = reactive({
      formData: {},
      trackData:{},

      positionTrajectory:[],//车辆定位数据
      trackSearchData: {},//轨迹搜索数据
      map: null,//地图
    });



    //地图加载
    const mapLoad = ()=> {
      state.map = new BMap.Map("_wz_vehicleMonitoring_allmap");    // 创建Map实例
      state.map.centerAndZoom(new BMap.Point(105.058886,36.028623), 4);  // 初始化地图,设置中心点坐标和地图级别
      //添加地图类型控件
      state.map.addControl(new BMap.MapTypeControl({
        mapTypes: [
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
        ]
      }));
      state.map.setCurrentCity("邢台");          // 设置地图显示的城市 此项是必须设置的
      state.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
      // 左上角，添加比例尺
      let top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});
      state.map.addControl(top_left_control);
      //左上角，添加默认缩放平移控件
      let top_left_navigation = new BMap.NavigationControl();
      state.map.addControl(top_left_navigation);
    }
    //搜索轨迹
    const trackFun = ()=> {
      state.trackData.carPlateNo = state.formData.vehiclePlateNo;//'冀E211N2';//
      //开始时间
      state.trackData.startTime = !!state.formData.beginDate?$common.timeFormatting(state.formData.beginDate, "yyyy-MM-dd hh:mm:ss"):$common.timeFormatting(new Date(), "yyyy-MM-dd hh:mm:ss");//'2021-02-25 00:00:00';//
      //结束时间
      state.trackData.endTime = !!state.formData.endDate?$common.timeFormatting(state.formData.endDate, "yyyy-MM-dd hh:mm:ss"):$common.timeFormatting(new Date(), "yyyy-MM-dd hh:mm:ss");//'2021-02-25 23:59:59';//
      state.spinShow = true;
      $axios.post(apiUrl.positionTrajectory, state.trackData).then(res => {
        state.spinShow = false;
        if (!!res) {
          state.positionTrajectory = res.data.data;
          if (!!res.data.data && res.data.data.length > 0) {
            state.trackSearchData = res.data.data[res.data.data.length - 1]
            ///////轨迹
            let line = [];
            res.data.data.forEach(function (k, i) {
              let marker;
              let myIcon = new BMap.Icon("img/vehicleImg/gj.png", new BMap.Size(15, 15));
              marker = new BMap.Marker(new BMap.Point(k.lonX, k.latY), {icon: myIcon});  // 创建标注
              marker.setRotation(k.direction);
              marker.setZIndex(99999);

              line.push(new BMap.Point(k.lonX, k.latY));//线连接点
            })
            let polyline = new BMap.Polyline(line, {
              strokeWeight: '3',//折线的宽度，以像素为单位
              strokeOpacity: 0.8,//折线的透明度，取值范围0 - 1
              strokeColor: "#18a45b" //折线颜色
            });   //
            state.map.addOverlay(polyline);          //增加折线
            state.map.setViewport(line);

            ///////轨迹
          } else {
            $ViewUIPlus.Message.error('暂未获得到该车辆的轨迹');
          }
        }
      }).catch(err => {
        console.log('失败', err);
      })

    }

    //加载数据
    const loadData = ()=>{
      $axios.post(apiUrl.safetyDrivingLogDrivingLogInfo, {uuid: props.currentTravelLogId}).then(res => {
        if (!!res) {
          state.formData = res.data.data;//出车信息
          trackFun();


          let marker;
          if (!!state.formData.beforeCheckLonX && !!state.formData.beforeCheckLatY) {//行车前
            let myIcon = new BMap.Icon("img/vehicleImg/start_q.png", new BMap.Size(28, 32));
            var point = new BMap.Point(state.formData.beforeCheckLonX, state.formData.beforeCheckLatY);
            marker = new BMap.Marker(point, {icon: myIcon});  // 创建标注
            marker.setZIndex(999999);
            state.map.addOverlay(marker);            //增加点

            marker.addEventListener('click', function () {
              state.map.openInfoWindow(new BMap.InfoWindow('检查时间：'+state.formData.beforeCheckTime, {width: 200,height: 100,title: '出车前检查'}), point); // 开启信息窗口
            });
          }
          if (!!state.formData.midwayCheckLonX && !!state.formData.midwayCheckLatY) {//行车前
            let myIcon = new BMap.Icon("img/vehicleImg/start_z.png", new BMap.Size(28, 32));
            var point = new BMap.Point(state.formData.midwayCheckLonX, state.formData.midwayCheckLatY);
            marker = new BMap.Marker(point, {icon: myIcon});  // 创建标注
            marker.setZIndex(999999);
            state.map.addOverlay(marker);            //增加点

            marker.addEventListener('click', function () {
              state.map.openInfoWindow(new BMap.InfoWindow('检查时间：'+state.drivingLogBic.masidwayCheckTime, {width: 200,height: 100,title: '行车中检查'}), point); // 开启信息窗口
            });
          }
          if (!!state.formData.afterCheckLonX && !!state.formData.afterCheckLatY) {//行车前
            let myIcon = new BMap.Icon("img/vehicleImg/start_h.png", new BMap.Size(28, 32));
            var point = new BMap.Point(state.formData.afterCheckLonX, state.formData.afterCheckLatY);
            marker = new BMap.Marker(point, {icon: myIcon});  // 创建标注
            marker.setZIndex(999999);
            state.map.addOverlay(marker);            //增加点
            marker.addEventListener('click', function () {
              state.map.openInfoWindow(new BMap.InfoWindow('检查时间：'+state.formData.afterCheckTime, {width: 200,height: 100,title: '收车后检查'}), point); // 开启信息窗口
            });
          }

        }
      }).catch(err => {
        console.log("失败", err)
      })
    }


    // 其他的生命周期
    onBeforeMount (() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted (() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")
      mapLoad();
      loadData();
    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate (() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated (() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount (() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted (() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
    }
  }
})


</script>


<style lang="less">
  ._wz_trajectory{
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
  }
</style>
